<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 页面工具栏 -->
      <PageTools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            round
            type="warning"
            @click="$router.push('/import')"
          >{{ $t('route.import') }}</el-button>
          <el-button
            size="small"
            round
            type="danger"
            @click="educeExcel"
          >{{ $t('route.derive') }}</el-button>
          <!-- 判断是与否有增加员工的功能,有显示,没有就不显示 -->
          <el-button
            v-if="
              showBtn('ADD')
            "
            size="small"
            round
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="employeeList" stripe>
          <el-table-column
            label="序号"
            sortable
            type="index"
            width="40"
            align="center"
            fixed="left"
          />
          <el-table-column
            label="头像"
            fixed="left"
            width="120"
          ><template
            slot-scope="{ row }"
          ><img
            v-imgerror="
              'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2986114791,2667770254&fm=26&gp=0.jpg'
            "
            :src="row.staffPhoto"
            class="staffPhoto"
            @click="showImg(row.staffPhoto)"
          ></template></el-table-column>
          <el-table-column
            label="姓名"
            sortable
            prop="username"
            align="center"
            fixed="left"
          />

          <el-table-column
            label="工号"
            sortable
            prop="workNumber"
            align="center"
          />
          <el-table-column
            label="聘用形式"
            sortable
            prop="formOfEmployment"
            :formatter="formatEmployment"
            align="center"
          />
          <el-table-column
            label="部门"
            sortable
            prop="departmentName"
            align="center"
          />
          <el-table-column
            label="入职时间"
            sortable
            prop="timeOfEntry"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            label="账户状态"
            sortable
            align="center"
            prop="enableState"
            width="150"
          >
            <template slot-scope="{ row }">
              <!-- 使用开关显示状态 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            fixed="right"
            width="300"
            align="center"
          >
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="toChangeRole(row.id)"
              >角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="toDelEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- 分页组件 -->
          <el-pagination
            :total="total"
            layout="sizes,total,prev,pager,next,jumper"
            :page-size="pages.size"
            :page-sizes="[4, 6, 8, 10]"
            @current-change="pageChange"
            @size-change="sizeChange"
          />
        </el-row>
      </el-card>
      <!-- 添加弹窗组件 -->
      <AddEmployee :show-dialog.sync="showDialog" />
      <!-- 添加 分配角色组件 -->
      <AssignRole ref="assignRoles" :to-role-data="toRoleData" />
      <!-- 生成二维码 -->
      <el-dialog
        title="二维码"
        :visible="showImgDialog"
        @close="showImgDialog = false"
      >
        <el-row type="flex" justify="center" align="middle">
          <canvas ref="mycanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import QRcode from 'qrcode'
import { getEmployeesList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from '@/views/employees/components/add-employee'
import AssignRole from '@/views/employees/components/assign-role'
import { formatDate } from '@/filters'

export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      // 传到分配角色的数据
      toRoleData: {
        showRoleDialog: false,
        userId: ''
      },
      showImgDialog: false,
      showDialog: false,
      loading: false,
      employeeList: [],
      total: 0,
      pages: {
        page: 1,
        size: 10
      }
    }
  },
  created() {
    this.toGetEmployeesList()
  },
  methods: {
    // 点击查看修改角色
    toChangeRole(id) {
      // 显示弹窗
      this.toRoleData.showRoleDialog = true
      this.toRoleData.userId = id
      // 触发组件的获取该用户基本信息的事件
      this.$refs.assignRoles.toGetUserDetailById(id)
    },
    // 生成二维码事件
    showImg(url) {
      // 有图片才显示
      if (url) {
        this.showImgDialog = true
      }
      // 需要等待页面渲染完成之后再进行下面的操作,可以使用this.$nextTick(执行的操作)
      this.$nextTick(() => {
        QRcode.toCanvas(this.$refs.mycanvas, url)
      })
    },
    // 导出员工excel文件
    async educeExcel() {
      // 重新获取所有员工数据
      const data = { page: this.pages.page, size: this.total }
      const { rows } = await getEmployeesList(data)
      // console.log(rows)
      // 懒加载使用导出方法,点击才引入使用第三方包
      const educeTools = import('@/vendor/Export2Excel')
      // then()是异步操作
      educeTools.then((item) => {
        // console.log(item)  有两个返回值
        // export_json_to_excel,export_table_to_excel
        const headers = {
          手机号: 'mobile',
          姓名: 'username',
          入职日期: 'timeOfEntry',
          聘用形式: 'formOfEmployment',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          部门: 'departmentName'
        }
        const data = rows.map((item) => {
          return this.toChangeDate(headers, item)
        })
        // console.log(data)
        // console.log(Object.keys(headers)) //Object.keys()是获取该对象的键
        // ["手机号", "姓名", "入职日期", "聘用形式", "转正日期", "工号", "部门"]
        // console.log('打印咯')
        item.export_json_to_excel({
          header: Object.keys(headers), // 表头
          data,
          filename: '员工信息表'
        })
      })
    },
    // 将数据改造成为二维数组函数
    toChangeDate(header, data) {
      const arr = []
      for (const key in header) {
        const newkey = header[key]
        if (newkey === 'timeOfEntry' || newkey === 'correctionTime') {
          // 转换日期数据合理化
          arr.push(formatDate(data[newkey], 'yyyy/MM/dd'))
        } else if (newkey === 'formOfEmployment') {
          // 在枚举中寻找相同,没有为false
          const en = EmployeeEnum.hireType.find(
            (obj) => obj.id === data[header[newkey]]
          )
          arr.push(en ? en.value : '未知')
        } else {
          arr.push(data[newkey])
        }
      }
      // console.log(arr)
      return arr
    },
    // 删除员工
    async toDelEmployee(id) {
      try {
        // 二次确认
        await this.$confirm('确认删除该员工吗?')
        await delEmployee(id)
        // 重新加载数据
        await this.toGetEmployeesList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // 要去找 1所对应的值
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 获取 员工列表
    async toGetEmployeesList() {
      const { total, rows } = await getEmployeesList(this.pages)
      this.total = total
      this.employeeList = rows
    },
    // 更换页
    pageChange(newPage) {
      // 将这个用户点击的新页码赋值给咱们配置 this.page
      this.pages.page = newPage
      this.toGetEmployeesList()
    },
    // 更换每页数量
    sizeChange(newPagesize) {
      // 将这个用户点击的新页码赋值给咱们配置 this.page
      this.pages.size = newPagesize
      this.toGetEmployeesList()
    }
  }
}
</script>

<style>
.staffPhoto {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 15px;
}
</style>
